{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import division, print_function, absolute_import\n",
    "import tflearn\n",
    "from tflearn.layers.core import dropout, fully_connected\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "from tflearn.layers.conv import conv_2d, max_pool_2d\n",
    "from tflearn.layers.normalization import local_response_normalization\n",
    "from tflearn.layers.estimator import regression\n",
    "\n",
    "# Data loading and preprocessing\n",
    "mnist = input_data.read_data_sets(\"/data/\", one_hot=True)\n",
    "X, Y, testX, testY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels\n",
    "X = X.reshape([-1, 28, 28, 1])\n",
    "testX = testX.reshape([-1, 28, 28, 1])\n",
    "\n",
    "# Building convolutional network\n",
    "network = tflearn.input_data(shape=[None, 28, 28, 1], name='input')\n",
    "network = conv_2d(network, 32, 3, activation='relu', regularizer=\"L2\")\n",
    "network = max_pool_2d(network, 2)\n",
    "network = local_response_normalization(network)\n",
    "network = conv_2d(network, 64, 3, activation='relu', regularizer=\"L2\")\n",
    "network = max_pool_2d(network, 2)\n",
    "network = local_response_normalization(network)\n",
    "network = fully_connected(network, 128, activation='tanh')\n",
    "network = dropout(network, 0.8)\n",
    "network = fully_connected(network, 256, activation='tanh')\n",
    "network = dropout(network, 0.8)\n",
    "network = fully_connected(network, 10, activation='softmax')\n",
    "network = regression(network, optimizer='adam', learning_rate=0.01,\n",
    "                     loss='categorical_crossentropy', name='target')\n",
    "\n",
    "# Training\n",
    "model = tflearn.DNN(network, tensorboard_verbose=0)\n",
    "model.fit({'input': X}, {'target': Y}, n_epoch=20,\n",
    "           validation_set=({'input': testX}, {'target': testY}),\n",
    "           snapshot_step=100, show_metric=True, run_id='convnet_mnist')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
